//绑定事件,初始化顶部数据
function initTopDate() {
    // 获取节点
    let ulYearObj = $('.year-select ul')
    let ulMonthObj = $('.month-select ul')
    //事件绑定
    $('.year-select').addEventListener('click', ulYearClick, false)
    $('.month-select').addEventListener('click', ulMonthClick, false)
    //绑定ul
    ulYearObj.addEventListener('click', yearUlClick, false)
    ulMonthObj.addEventListener('click', monthUlClick, false)
    //绑定切换事件,监听，转换到月则能切换日期，转换到年则能够切换月份
    $('.switchTo .switchToMonth').addEventListener('click', changeDay, false)
    $('.switchTo .switchToYear').addEventListener('click', changeMonth, false)
    //添加li
    let yearHtml = ''
    for (let t = 2015; t <= 2025; t++) {
        yearHtml += `<li>${t}年</li>`
    }
    ulYearObj.innerHTML = yearHtml

    let monthHtml = ''
    for (let i = 1; i <= 12; i++) {
        monthHtml += `<li>${i}月</li>`
    }
    ulMonthObj.innerHTML = monthHtml
}
//点击事件，点击出现下拉框
function ulYearClick(e) {
    stopPropagation(e)
    let ulObj = $('.year-select ul')
    if (ulObj.style.display === 'block') {
        ulObj.style.display = 'none'
    } else {
        ulObj.style.display = "block"
    }
}

function ulMonthClick(e) {
    stopPropagation(e)
    let ulObj = $('.month-select ul')
    if (ulObj.style.display === 'block') {
        ulObj.style.display = 'none'
    } else {
        ulObj.style.display = "block"
    }
}
//点击切换到年
function yearUlClick(e) {
    stopPropagation(e)
    let year = $('.year-select .year')
    $('.bgColor').classList.remove('bgColor')
    year.innerHTML = e.target.innerHTML
    console.log(changeTime.toLocaleDateString());
    changeTimeObj(parseInt(year.innerHTML), '', '')
    addTimeTitle()
    //重绘月份
    monthNew()
    $(`[title="${changeTime.toLocaleDateString()}"]`).classList.add('bgColor')

    $('.year-select ul').style.display = 'none'
}
// 切换到月
function monthUlClick(e) {
    stopPropagation(e)
    let month = $('.month-select .month')
    $('.bgColor').classList.remove('bgColor')
    month.innerHTML = e.target.innerHTML
    changeTimeObj('', parseInt(month.innerHTML), '')
    addTimeTitle()
    $('.month-select ul').style.display = 'none'
}

//切换点击事件
function changeDay(e) {
    stopPropagation(e)
    //切换样式
    $('.active').classList.remove('active')
    this.classList.add('active')
    $('#months').style.display = 'none'
    $('#days').style.opacity = 1
    $('.month-select').style.display = 'block'

}

function changeMonth(e) {
    stopPropagation(e)
    $('.active').classList.remove('active')
    this.classList.add('active')
    $('#months').style.display = 'block'
    $('#days').style.opacity = 0
    $('.month-select').style.display = 'none'
}
//为月份添加title
function monthNew() {
    addMonth()
    //获取当前年份
    let year = changeTime.getFullYear()
    Array.from($('.months').children, (item, index) => {
        let time = index + 1 < 10 ? year + '/0' + (index + 1) : year + '/' + (index + 1)
        item.setAttribute('title', time)
        if (changeTime.toLocaleDateString().indexOf(item.getAttribute("title")) !== -1) {
            item.classList.add('bgMonthColor')
        }
    })
    //获取月份添加样式
    let yearWithMonth = nowTime.getFullYear() + '/' + ((nowTime.getMonth() + 1) < 10 ? '0' + (nowTime.getMonth() + 1) : (nowTime.getMonth() + 1))
    let nowYearWithMonth = changeTime.getFullYear() + '/' + ((changeTime.getMonth() + 1) < 10 ? '0' + (changeTime.getMonth() + 1) : (changeTime.getMonth() + 1))
    $(`[title="${nowYearWithMonth}"]`).classList.add('bgMonthColor')
    let judge = $(`[title="${yearWithMonth}"]`)
    if (!!judge) {
        judge.classList.add('thBorder')
    }
}

//填充月份数据
function addMonth() {
    $('.months').innerHTML = ''
    let html = ''
    for (let i = 1; i <= 12; i++) {
        html += `<div onclick="monthClick(this)">${i}月</div>`
    }
    $('.months').innerHTML = html
}
//给body添加事件
$('body').addEventListener('click', () => {
    $('.year-select ul').style.display = 'none'
    $('.month-select ul').style.display = 'none'
})

//当前时间
var nowTime = new Date()
// 改变的时间
var changeTime = new Date()
//初始化星期数
async function week() {
    let week = ['一', '二', '三', '四', '五', '六', '日']
    //获取节点
    let tr = $('.week tr')
    let html = ''
    for (i of week) {
        html += `<th>${i}</th>`
    }
    tr.innerHTML = html
    await addTr()
}

//添加日
async function addTr() {
    let tbodyTr = $('#days tbody')
    let html = ''
    for (let i = 0; i < 6; i++) {
        html += `<tr>${addDay(i)}</tr>`
    }
    tbodyTr.innerHTML = html
    //为th添加自定义title
    addTimeTitle()
}

//添加天数
function addDay(index) {
    let html = ''
    for (let i = 1; i <= 7; i++) {
        if (index < 1) {
            // sign="sign"使负数转为正数
            html += `<th sign="sign" onclick="thClick(this)"></th>`
        } else {
            html += `<th onclick="thClick(this)"></th>`
        }
    }
    return html
}

//更新
function addTimeTitle() {
    //获取节点
    let tbodyNodes = document.querySelectorAll('#days tbody th')
    let nowWeek = changeTime.getDay()
    let count = getMonthDay()
    // console.log(changeTime.toLocaleDateString());
    // let today = changeTime.getDate()
    let nowYear = changeTime.getFullYear()
    let nowMonth = changeTime.getMonth()
    let judgeTime = new Date(nowYear, nowMonth, 1)
    let countDay = 1
    let oneWeek = judgeTime.getDay()

    // console.log(oneWeek);
    Array.from(tbodyNodes, (item, index) => {
        //每次更新清除
        item.removeAttribute('title')
        item.innerHTML = ''
        if (oneWeek <= index + 1 && countDay <= count) {
            let year = changeTime.getFullYear()
            let month = changeTime.getMonth()
            //添加title
            item.setAttribute('title', year + '/' + (month + 1) + '/' + countDay)
            item.innerHTML = countDay < 10 ? '0' + countDay : countDay
            countDay++
        }
    })
    //如果有删除原有的border颜色
    let borderTop = $('.thBorder')
    if (borderTop) {
        borderTop.classList.remove('thBorder')
    }
    let bgColor = $('.bgColor')
    if (!!bgColor) {
        bgColor.classList.remove('bgColor')
    }
    //添加背景颜色
    $(`[title="${changeTime.toLocaleDateString()}"]`).classList.add('bgColor')
    //给当前时间添加样式
    let nowTimeDay = $(`[title="${nowTime.toLocaleDateString()}"]`)
    if (nowTimeDay !== null) {
        nowTimeDay.classList.add('thBorder')
    }
}

//获取当前月份天数
function getMonthDay() {
    let year = changeTime.getFullYear()
    let month = changeTime.getMonth()
    let newDate = new Date(year, month + 1, 0)
    let countMonth = newDate.getDate()
    return countMonth
}

//点击改变背景
function thClick(that) {
    $('.bgColor').classList.remove('bgColor')
    that.classList.add('bgColor')
    //点击后改变changeTime
    let day = parseInt(that.innerHTML)
    changeTimeObj('', '', day)
    // console.log(changeTime.toLocaleDateString());
    let value = that.innerHTML
    let signs = that.getAttribute('sign')
    //判断点击是否向前一个月跳转
    if (!value) {
        //点击开头
        if (!!signs) {
            let monthNode = $('.month')
            if (parseInt(monthNode.innerHTML) === 1) {
                monthNode.innerHTML = 12 + '月'
                $('.year').innerHTML = changeTime.getFullYear() - 1 + '年'
                //跟新时间
                changeTimeObj(parseInt($('.year').innerHTML), parseInt(monthNode.innerHTML), '')
            } else {
                let monthNode = $('.month')
                changeTimeObj('', changeTime.getMonth(), '')
                monthNode.innerHTML = changeTime.getMonth() + 1 + '月'
            }
            addTimeTitle()
        } else { //点击尾部
            let monthNode = $('.month')
            if (parseInt(monthNode.innerHTML) === 12) {
                monthNode.innerHTML = 1 + '月'
                // console.log(changeTime.getFullYear());
                $('.year').innerHTML = changeTime.getFullYear() + 1 + '年'
                //跟新时间
                changeTimeObj(parseInt($('.year').innerHTML), parseInt(monthNode.innerHTML), '')
                // console.log(changeTime.toLocaleDateString());
            } else {
                // console.log(changeTime.toLocaleDateString());
                changeTimeObj('', (changeTime.getMonth() + 1) + 1, '')
                // console.log(changeTime.getMonth());
                monthNode.innerHTML = (changeTime.getMonth() + 1) + '月'
                // console.log(changeTime.toLocaleDateString());
                // console.log(changeTime.getMonth() + 1 + 1);
            }
            addTimeTitle()
        }
    }

}

//改变changeTime函数
function changeTimeObj(yearObj, monthObj, dayObj) {
    let year = ''
    let month = ''
    let day = ''
    if (yearObj) {
        year = yearObj
    } else {
        year = changeTime.getFullYear()
    }
    if (monthObj) {
        month = monthObj
    } else {
        month = changeTime.getMonth() + 1
    }
    if (dayObj) {
        day = dayObj
    } else {
        day = changeTime.getDate()
    }
    // console.log(year+'---'+month+'---'+day);
    changeTime = new Date(year, month - 1, day)
    // console.log(changeTime.toLocaleDateString());
}
//月份点击
function monthClick(that) {
    let bgMonthColorTmp = $('.bgMonthColor')
    let month = $('.month')
    bgMonthColorTmp.classList.remove('bgMonthColor')
    that.classList.add('bgMonthColor')
    month.innerHTML = that.innerHTML
    //改变时间
    changeTimeObj('', parseInt(month.innerHTML), '')
    addTimeTitle()
}


//日期
function initDate() {
    initTopDate()
    //添加月
    monthNew()

    //初始化样式
    let nowActive = changeTime.getFullYear() + '/' + (changeTime.getMonth() + 1)
    let nowStyle = $(`[title="${nowActive}"]`)
    nowStyle.classList.add('thMonthBorder')
    // nowStyle.classList.add('bgMonthColor')
}

//获取节点方法
function $(tag) {
    return document.querySelector(tag)
}
// 防止点击到年月的选择框
function stopPropagation(e) {
    if (e.stopPropagation) {
        e.stopPropagation();
    } else {
        e.cacelBubble = true;
    }
}

//初始化页面
week()
//初始化日期选择
initDate()